<template>
    <div class="indicator-analysis">
        <el-card>
            <el-tabs v-model="activeTab">
                <!-- 指标配置页 -->
                <el-tab-pane label="指标配置" name="config">
                    <el-form :inline="true" label-width="100px" class="config-form">
                        <el-form-item label="统计项">
                            <el-checkbox-group v-model="config.selectedIndicators">
                                <el-checkbox v-for="item in indicatorOptions" :key="item.value" :label="item.value">
                                    {{ item.label }}
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                        <el-form-item label="统计周期">
                            <el-radio-group v-model="config.period">
                                <el-radio label="day">日</el-radio>
                                <el-radio label="week">周</el-radio>
                                <el-radio label="month">月</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="统计维度">
                            <el-radio-group v-model="config.dimension">
                                <el-radio label="workshop">车间</el-radio>
                                <el-radio label="equipmentType">设备类型</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="saveConfig">保存配置</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>

                <!-- 分析看板页 -->
                <el-tab-pane label="分析看板" name="dashboard">
                    <el-row :gutter="20" class="dashboard-controls">
                        <el-col :span="6">
                            <el-select v-model="chartType" placeholder="选择图表类型" style="width: 100%">
                                <el-option label="OEE对比（柱状图）" value="bar"></el-option>
                                <el-option label="维护成本趋势（折线图）" value="line"></el-option>
                                <el-option label="故障类型占比（饼图）" value="pie"></el-option>
                            </el-select>
                        </el-col>
                        <el-col :span="6" v-if="chartType === 'bar' || chartType === 'line'">
                            <el-date-picker v-model="dateRange" type="daterange" range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions"
                                style="width: 100%"></el-date-picker>
                        </el-col>
                    </el-row>
                    <div class="chart-container">
                        <div v-show="chartType === 'bar'" style="height: 400px;">
                            <v-chart :option="barOption" autoresize @click="handleBarClick" />
                        </div>
                        <div v-show="chartType === 'line'" style="height: 400px;">
                            <v-chart :option="lineOption" autoresize />
                        </div>
                        <div v-show="chartType === 'pie'" style="height: 400px;">
                            <v-chart :option="pieOption" autoresize @click="handlePieClick" />
                        </div>
                    </div>
                    <!-- 下钻弹窗 -->
                    <el-dialog :visible.sync="drillDialogVisible" width="600px" :title="drillTitle">
                        <el-table :data="drillData" border>
                            <el-table-column prop="name" label="设备名称" width="180" />
                            <el-table-column prop="oee" label="OEE(%)" />
                            <el-table-column prop="cost" label="维护成本(元)" />
                            <el-table-column prop="fault" label="故障类型" />
                        </el-table>
                    </el-dialog>
                </el-tab-pane>
            </el-tabs>
        </el-card>
    </div>
</template>

<script>
    import { mapState } from 'vuex'
    import ECharts from 'vue-echarts/components/ECharts.vue'
    import 'echarts/lib/chart/bar'
    import 'echarts/lib/chart/line'
    import 'echarts/lib/chart/pie'
    import 'echarts/lib/component/tooltip'
    import 'echarts/lib/component/legend'
    import 'echarts/lib/component/title'

    // mock 车间、设备类型、设备、故障类型
    const workshops = [
        { name: '装配车间', id: 'assembly' },
        { name: '机加工车间', id: 'machining' }
    ]
    const equipmentTypes = [
        { name: '数控机床', id: 'cnc' },
        { name: '机器人', id: 'robot' }
    ]
    const devices = [
        { name: '装配1号机', workshop: 'assembly', type: 'cnc' },
        { name: '装配2号机', workshop: 'assembly', type: 'robot' },
        { name: '机加1号机', workshop: 'machining', type: 'cnc' },
        { name: '机加2号机', workshop: 'machining', type: 'robot' }
    ]
    const faultTypes = [
        { name: '电气故障', id: 'electrical' },
        { name: '机械故障', id: 'mechanical' },
        { name: '传感器故障', id: 'sensor' }
    ]

    // mock 数据生成
    function randomData() {
        // 生成近半年日期
        const dates = []
        const now = new Date()
        for (let i = 5; i >= 0; i--) {
            const d = new Date(now.getFullYear(), now.getMonth() - i, 1)
            dates.push(`${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}`)
        }
        // OEE mock
        const oee = {
            assembly: 85,
            machining: 78
        }
        // 维护成本 mock
        const cost = {
            assembly: [12000, 11000, 10500, 10000, 9800, 9500],
            machining: [15000, 14000, 13500, 13000, 12800, 12500]
        }
        // 故障类型 mock
        const faults = [
            { name: '电气故障', value: 12 },
            { name: '机械故障', value: 8 },
            { name: '传感器故障', value: 5 }
        ]
        // 设备下钻 mock
        const drill = [
            { name: '装配1号机', oee: 87, cost: 4800, fault: '电气故障' },
            { name: '装配2号机', oee: 83, cost: 4700, fault: '机械故障' },
            { name: '机加1号机', oee: 80, cost: 6200, fault: '电气故障' },
            { name: '机加2号机', oee: 76, cost: 6300, fault: '传感器故障' }
        ]
        return { dates, oee, cost, faults, drill }
    }

    export default {
        name: 'StatisticalAnalysisOfIndicators',
        components: {
            'v-chart': ECharts
        },
        data() {
            return {
                activeTab: 'config',
                // 指标配置
                indicatorOptions: [
                    { label: '非计划停机时间减少率', value: 'downtime' },
                    { label: '维护成本下降率', value: 'cost' },
                    { label: 'OEE', value: 'oee' }
                ],
                config: {
                    selectedIndicators: [],
                    period: 'month',
                    dimension: 'workshop'
                },
                // 分析看板
                chartType: 'bar',
                dateRange: [],
                pickerOptions: {
                    disabledDate: () => false
                },
                // mock 数据
                mock: randomData(),
                // 下钻
                drillDialogVisible: false,
                drillData: [],
                drillTitle: ''
            }
        },
        computed: {
            barOption() {
                // 柱状图：各车间OEE对比
                return {
                    title: { text: '各车间OEE对比', left: 'center' },
                    tooltip: {},
                    xAxis: {
                        type: 'category',
                        data: workshops.map(w => w.name)
                    },
                    yAxis: { type: 'value', min: 0, max: 100, axisLabel: { formatter: '{value}%' } },
                    series: [
                        {
                            name: 'OEE',
                            type: 'bar',
                            data: workshops.map(w => this.mock.oee[w.id]),
                            itemStyle: { color: '#409EFF' }
                        }
                    ]
                }
            },
            lineOption() {
                // 折线图：维护成本趋势
                return {
                    title: { text: '维护成本趋势', left: 'center' },
                    tooltip: { trigger: 'axis' },
                    legend: { data: workshops.map(w => w.name), top: 30 },
                    xAxis: {
                        type: 'category',
                        data: this.mock.dates
                    },
                    yAxis: { type: 'value', name: '维护成本(元)' },
                    series: workshops.map(w => ({
                        name: w.name,
                        type: 'line',
                        data: this.mock.cost[w.id],
                        smooth: true
                    }))
                }
            },
            pieOption() {
                // 饼图：故障类型占比
                return {
                    title: { text: '故障类型占比', left: 'center' },
                    tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
                    legend: { orient: 'vertical', left: 10, data: this.mock.faults.map(f => f.name) },
                    series: [
                        {
                            name: '故障类型',
                            type: 'pie',
                            radius: '60%',
                            center: ['50%', '60%'],
                            data: this.mock.faults,
                            emphasis: {
                                itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' }
                            }
                        }
                    ]
                }
            }
        },
        created() {
            this.loadConfig()
            // 默认日期范围：近半年
            const now = new Date()
            const start = new Date(now.getFullYear(), now.getMonth() - 5, 1)
            this.dateRange = [start, now]
        },
        methods: {
            saveConfig() {
                localStorage.setItem('indicatorConfig', JSON.stringify(this.config))
                this.$message.success('配置已保存！')
            },
            loadConfig() {
                const cfg = localStorage.getItem('indicatorConfig')
                if (cfg) {
                    this.config = JSON.parse(cfg)
                }
            },
            handleBarClick(params) {
                // 柱状图下钻：点击车间，弹窗显示该车间设备数据
                if (params && params.name) {
                    const workshopId = workshops.find(w => w.name === params.name).id
                    this.drillData = this.mock.drill.filter(d => {
                        return devices.find(dev => dev.name === d.name && dev.workshop === workshopId)
                    })
                    this.drillTitle = params.name + ' 设备OEE与维护成本'
                    this.drillDialogVisible = true
                }
            },
            handlePieClick(params) {
                // 饼图下钻：点击故障类型，弹窗显示该类型设备
                if (params && params.name) {
                    this.drillData = this.mock.drill.filter(d => d.fault === params.name)
                    this.drillTitle = params.name + ' 相关设备'
                    this.drillDialogVisible = true
                }
            }
        }
    }
</script>

<style scoped>
    .indicator-analysis {
        padding: 20px;
    }

    .config-form {
        margin-top: 20px;
    }

    .dashboard-controls {
        margin-bottom: 20px;
    }

    .chart-container {
        background: #fff;
        padding: 20px;
        border-radius: 6px;
        min-height: 420px;
    }
</style>